package cn.dankal.flyaudio.friend;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter;
import com.donkingliang.groupedadapter.holder.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.base.recyclerview.OnRvItemClickListener;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.SimpleTextChange;
import cn.dankal.basiclib.widget.ClearEditText;
import cn.dankal.flyaudio.FlyApplication;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.ContractPersonAdapter;
import cn.dankal.flyaudio.adapter.SearchUserAdapter;
import cn.dankal.flyaudio.entity.GroupEntity;
import cn.dankal.flyaudio.friend.utils.pinyin.HanziToPinyin;
import cn.dankal.flyaudio.personal.PersonalProfileActivity;
import cn.dankal.flyaudio.view.LetterNavView;
import cn.jpush.im.android.api.ContactManager;
import cn.jpush.im.android.api.callback.GetUserInfoListCallback;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.UserInfo;

public class ContractPersonActivity extends BaseActivity implements View.OnClickListener {

    private RecyclerView friendView;
    private LetterNavView navView;

    private ContractPersonAdapter adapter;

    private SearchUserAdapter searchUserAdapter;

    private TextView titleView;

    private TextView confirmView;

    private TextView searchTextView;
    private View newFriendView;
    private View newFriendLineView;
    private View groupView;
    private ClearEditText searchEditText;
    private TextView numView;
    private TextView groupNumView;

    private MultipleStatusView statusView;

    private List<GroupEntity> personEntities = new ArrayList<>();

    private List<UserInfo> friendList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_contract_person;
    }

    private void initSearch() {
        statusView = findViewById(R.id.multiple_status_view);
        searchTextView = findViewById(R.id.tv_search);
        searchEditText = findViewById(R.id.et_search);
        numView = findViewById(R.id.tv_system_public_number);
        groupNumView = findViewById(R.id.tv_system_public_group_number);
        findViewById(R.id.iv_onback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        searchEditText.setOnSearchListener(new ClearEditText.OnSearchListener() {
            @Override
            public void doSearch(String keyword) {
                if (TextUtils.isEmpty(keyword)) return;
                ContractPersonActivity.this.doSearch(keyword);
            }
        });
        searchTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = searchEditText.getText().toString();
                if (TextUtils.isEmpty(key)) return;
                doSearch(key);
            }
        });
        if (SharePreferenceManager.getCachedNewFriendNum() > 0) {
            numView.setText(SharePreferenceManager.getCachedNewFriendNum() + "");
            numView.setVisibility(View.VISIBLE);
        } else {
            numView.setVisibility(View.GONE);
        }
        if (SharePreferenceManager.getCachedNewGroupInvateNum() > 0) {
            groupNumView.setText(SharePreferenceManager.getCachedNewGroupInvateNum() + "");
            groupNumView.setVisibility(View.VISIBLE);
        } else {
            groupNumView.setVisibility(View.GONE);
        }

        searchEditText.addTextChangedListener(new SimpleTextChange() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                if (TextUtils.isEmpty(s)) {
                    friendView.setAdapter(adapter);
                    groupView.setVisibility(View.VISIBLE);
                    newFriendLineView.setVisibility(View.VISIBLE);
                    newFriendView.setVisibility(View.VISIBLE);
                    statusView.showContent();
                }
            }
        });
        statusView.showContent();
    }
    public void dismissNewFriends() {
        SharePreferenceManager.setCachedNewFriendNum(0);
//        FlyApplication.forAddIntoGroup.clear();
        FlyApplication.forAddFriend.clear();
        numView.setVisibility(View.GONE);
    }

    public void dismissNewGroup() {
        SharePreferenceManager.setCachedNewGroupNum(0);
        FlyApplication.forAddIntoGroup.clear();
        groupNumView.setVisibility(View.GONE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //刷新气泡
        if(groupNumView != null){
            if (SharePreferenceManager.getCachedNewGroupInvateNum() > 0) {
                groupNumView.setText(SharePreferenceManager.getCachedNewGroupInvateNum() + "");
                groupNumView.setVisibility(View.VISIBLE);
            } else {
                groupNumView.setVisibility(View.GONE);
            }

            //重新获取列表数据
            ContactManager.getFriendList(new GetUserInfoListCallback() {
                @Override
                public void gotResult(int i, String s, List<UserInfo> list) {
                    handleFriend(list);
                }
            });
        }
    }

    @Override
    protected void initComponents() {
        friendView = findViewById(R.id.rv_friend);
        navView = findViewById(R.id.letter_container);
        initSearch();
        confirmView = findViewById(R.id.tv_confirm);
        titleView = findViewById(R.id.tv_title);
        groupView = findViewById(R.id.rl_group_layout);
        newFriendView = findViewById(R.id.rl_new_friend_layout);
        newFriendLineView = findViewById(R.id.rl_new_friend_line);

//        personEntities.addAll(TestData.getContractPerson());
        friendView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ContractPersonAdapter(this, personEntities);
        searchUserAdapter = new SearchUserAdapter();
        searchUserAdapter.setOnRvItemClickListener(new OnRvItemClickListener<UserInfo>() {
            @Override
            public void onItemClick(View v, int position, UserInfo data) {
                Intent intent = new Intent(ContractPersonActivity.this, PersonalProfileActivity.class);
                intent.putExtra("userId", data.getUserName());
                startActivity(intent);
            }
        });
        friendView.setAdapter(adapter);
        findViewById(R.id.iv_friend_add).setOnClickListener(this);
        findViewById(R.id.rl_new_friend_layout).setOnClickListener(this);
        findViewById(R.id.rl_group_layout).setOnClickListener(this);
        ContactManager.getFriendList(new GetUserInfoListCallback() {
            @Override
            public void gotResult(int i, String s, List<UserInfo> list) {
                handleFriend(list);
            }
        });
        navView.setLetterChangeListener(new LetterNavView.LetterChangeListener() {
            @Override
            public void onTouchingLetterChanged(int index, String text) {
                int count = 0;
                for (int i = 0; i < index; i++) {
                    count++;
                    if (personEntities.isEmpty()) {
                        return;
                    }
                    count += personEntities.get(i).getChildren().size();
                }
                if (count != -1) {
                    friendView.scrollToPosition(count);
                    LinearLayoutManager mLayoutManager =
                            (LinearLayoutManager) friendView.getLayoutManager();
                    mLayoutManager.scrollToPositionWithOffset(count, 0);
                }
//                friendView.scrollToPosition(count);
            }
        });
        adapter.setOnChildClickListener(new GroupedRecyclerViewAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(GroupedRecyclerViewAdapter adapter, BaseViewHolder holder, int groupPosition, int childPosition) {
                UserInfo userInfo = ContractPersonActivity.this.adapter.getData().get(groupPosition).getChildren().get(childPosition);
                Intent intent = new Intent(ContractPersonActivity.this, PersonalProfileActivity.class);
                intent.putExtra("userId", userInfo.getUserName());
                startActivity(intent);
//                toChat(groupPosition,childPosition);
            }
        });
        confirmView.setOnClickListener(this);
    }

    private void doSearch(String key) {
        List<UserInfo> searResult = new ArrayList<>();
        for (UserInfo userInfo : friendList) {
            ArrayList<HanziToPinyin.Token> tokens = HanziToPinyin.getInstance()
                    .get(userInfo.getNickname());
            StringBuilder sb = new StringBuilder();
            if (tokens != null && tokens.size() > 0) {
                for (HanziToPinyin.Token token : tokens) {
                    if (token.type == HanziToPinyin.Token.PINYIN) {
                        sb.append(token.target);
                    } else {
                        sb.append(token.source);
                    }
                }
            }
            if (sb.toString().contains(key) || userInfo.getNickname().contains(key)) {
                searResult.add(userInfo);
            }
        }
        if (searResult.isEmpty()) {
            statusView.showEmpty();
            findViewById(R.id.status_hint_content_1).setVisibility(View.GONE);
        } else {
            searchUserAdapter.addDatas(searResult, true);
            statusView.showContent();
            findViewById(R.id.status_hint_content_1).setVisibility(View.VISIBLE);
            friendView.setAdapter(searchUserAdapter);
            groupView.setVisibility(View.GONE);
            newFriendLineView.setVisibility(View.GONE);
            newFriendView.setVisibility(View.GONE);
        }
    }

    private void toChat(int parentPos, int childPos) {
        Intent intent = new Intent();
        UserInfo userInfo = adapter.getData().get(parentPos).getChildren().get(childPos);
        Conversation conv = Conversation.createSingleConversation(userInfo.getUserName(), userInfo.getAppKey());
        intent.putExtra(FlyApplication.CONV_TITLE, conv.getTitle());

        String targetId = ((UserInfo) conv.getTargetInfo()).getUserName();
        intent.putExtra(FlyApplication.TARGET_ID, targetId);
        intent.putExtra(FlyApplication.TARGET_APP_KEY, conv.getTargetAppKey());
        intent.setClass(ActivityUtils.getTopActivity(), ChatActivity.class);
        ActivityUtils.startActivity(intent);

    }

    List<GroupEntity> groupEntities = new ArrayList<>();

    private void handleFriend(List<UserInfo> list) {
        friendList.clear();
        friendList.addAll(list);
        groupEntities.clear();
        for (UserInfo userInfo : list) {
            String letter = getLetter(userInfo.getNickname());
            if (!checkGroupSave(letter)) {
                GroupEntity groupEntity = new GroupEntity();
                groupEntity.setHeader(letter);
                groupEntities.add(groupEntity);
            }
            GroupEntity groupEntity = getGroupByLetter(letter);
            if (groupEntity != null) {
                List<UserInfo> userInfos = groupEntity.getChildren();
                userInfos.add(userInfo);
                groupEntity.setChildren(userInfos);
            }
        }
        adapter.setNewData(groupEntities);
    }

    private boolean checkGroupSave(String letter) {
        for (GroupEntity entity : groupEntities) {
            if (entity.getHeader().contains(letter)) {
                return true;
            }
        }
        return false;
    }

    private GroupEntity getGroupByLetter(String letter) {
        for (GroupEntity entity : groupEntities) {
            if (entity.getHeader().contains(letter)) {
                return entity;
            }
        }
        return null;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.rl_new_friend_layout:
                dismissNewFriends();
                ActivityUtils.startActivity(NewFriendActivity.class);
                break;
            case R.id.rl_group_layout:
//                dismissNewGroup();
                ActivityUtils.startActivity(GroupActivity.class);
                break;
            case R.id.iv_friend_add:
                ActivityUtils.startActivity(AddFriendActivity.class);
                break;
        }
    }

    private String getLetter(String name) {
        String letter;
        ArrayList<HanziToPinyin.Token> tokens = HanziToPinyin.getInstance()
                .get(name);
        StringBuilder sb = new StringBuilder();
        if (tokens != null && tokens.size() > 0) {
            for (HanziToPinyin.Token token : tokens) {
                if (token.type == HanziToPinyin.Token.PINYIN) {
                    sb.append(token.target);
                } else {
                    sb.append(token.source);
                }
            }
        }
        String sortString = sb.toString().substring(0, 1).toUpperCase();
        if (sortString.matches("[A-Z]")) {
            letter = sortString.toUpperCase();
        } else {
            letter = "#";
        }
        return letter;
    }

}
